﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameDb;
using GameWeb.Models;
using GameDb.Entities;
using System.Web.Script.Serialization;

namespace GameWeb.Controllers
{
    public class GameMaintenanceController : BaseController
    {
        //
        // GET: /GameMaintenance/

        [Authorize]
        public ActionResult Index()
        {
            var model = GameCtx.Use(
                ctx =>
                {
                    var game = GameCtx.GetGameRecord(ctx);
                    var users = ctx.Users.ToList();

                    var gameMatches = ctx.Users.Where(ur => ur.Username == User.Identity.Name).Join(ctx.MatchPlayers,
                            us => us.UserId, mp => mp.UserId, (us, mp) => mp.GameMatch).Distinct().ToList();

                    return new GameMaintenanceModel
                    {
                        AllPlayers = users.Select(us => new PlayerSelectModel
                        {
                            Id = us.UserId,
                            UserName = us.Username
                        }),
                        OtherPlayers = users.Where(ur => ur.Username != User.Identity.Name).Select(us => new PlayerSelectModel
                        {
                            Id = us.UserId,
                            UserName = us.Username
                        }),
                        GameMatches = gameMatches.Select(gm => new GameMatch
                        {
                            GameMatchId = gm.GameMatchId,
                            StartDate = gm.StartDate,
                            PlayerDisplay = gm.PlayerDisplay
                        }).ToList(),
                    };
                });

            return View(model);
        }

        [HttpPost]
        [Authorize]
        public JsonResult CreateGame(IEnumerable<PlayerSelectModel> players)
        {
            var startTime = DateTime.Now;
            var newMatch = GameCtx.Use(
                (ctx, ts) =>
                {
                    var game = GameCtx.GetGameRecord(ctx);
                    var match = new GameMatch { Game = game, StartDate = startTime, NumberOfTrayPieces = 6, CountOfEachPieceType = 3 };
                    game.GameMatches.Add(match);
                    var playerList = new List<User>();
                    playerList.Add(GameCtx.GetCurrentUser(ctx));
                    foreach (var psm in players.Where(psm => psm.IsChecked))
                        playerList.Add(ctx.Users.Where(us => us.UserId == psm.Id).Single());

                     var matchTurn = new MatchTurn
                    {
                        MatchTurnNumber = 0,
                        GameMatch = match,
						StartDate = startTime
                    };

                    ctx.MatchTurns.Add(matchTurn);

                   var rndNdx = 0;
                    var playerShuffle = playerList.Shuffle(new Random(DateTime.Now.Millisecond)).ToList();
                    foreach (var player in playerShuffle)
                    {
						var matchPlayer = new MatchPlayer
                        {
                            User = player,
                            TurnSequence = (short)rndNdx++
                        };
                        match.MatchPlayers.Add(matchPlayer);
						
						 var matchPlayerTurn = new MatchPlayerTurn
						{
							MatchTurn = matchTurn,
							TurnSequence = matchPlayer.TurnSequence,
							MatchPlayer = matchPlayer
						};

						if (matchPlayer.TurnSequence == 0)
                            matchPlayerTurn.StartDate = startTime;
						matchTurn.MatchPlayerTurns.Add(matchPlayerTurn);
                   }

                    //generate pieces - 3 of each type
                    for (var typeNdx = 0; typeNdx < match.CountOfEachPieceType; typeNdx++)
                    {
                        for (var colorNdx = 0; colorNdx < 6; colorNdx++)
                        {
                            for (var shapeNdx = 0; shapeNdx < 6; shapeNdx++)
                            {
                                match.MatchPieces.Add(new MatchPiece
                                 {
                                     GameMatch = match,
                                     ColorIndex = colorNdx,
                                     ShapeIndex = shapeNdx,
                                 });
                            }
                        }
                    }

                    foreach (var matchPlayerTurn in matchTurn.MatchPlayerTurns)
                    {
                        match.SelectPieces(matchPlayerTurn, match.NumberOfTrayPieces);
                    }

                    ctx.SaveChanges();

                    return match;
                });

            return Json(new { matchId = newMatch.GameMatchId, status = "ok" });
        }

    }
}
